const SerialPort = require('serialport')
const fs = require('fs')
const chalk = require('chalk');
//读取配置文件
const config = JSON.parse(fs.readFileSync('./config.json'))
const _DEBUG = config.DEBUG
//用户输入串口
// const readlineSync = require('readline-sync')
// console.log("请输入串口（如COM2，默认COM2回车即可）")
// let com = readlineSync.question(":")
// if(com==null||com=='') com = "COM2"
//监控数据
const monitor = new require('./module/monitor')(config)
let com = config.port
const port = new SerialPort(com, {
  baudRate: config.baudRate,
  autoOpen: true
})
//端口占用就退出
port.on('error',()=>process.exit())

//创建log目录
if(!fs.existsSync("log"))
  fs.mkdirSync("log")
if(!fs.existsSync("./log/"+new Date().toLocaleDateString()))
  fs.mkdirSync("./log/"+new Date().toLocaleDateString())
//文件管理
const file = {
  name:new Date().getTime() + '.txt',
  append:text=>{
    if(_DEBUG)console.log(text);
    fs.appendFileSync(`./log/${new Date().toLocaleDateString() + '/' + file.name}`,`${new Date().toLocaleString()} : ${text} \n`)
  }
}
//发送串口内容
function sendMsg(){
  monitor.sendData = randomChar()
  // console.log("发送数据："+ monitor.sendData)
  port.write(monitor.sendData, function(err) {
    if (err) {
      return console.log('Error on write: ', err.message)
    }
    monitor.recivedData = ''
    monitor.count ++
    monitor.timer = config.interval
    console.log(`这是发送的第${monitor.count}包`)
  })
}
//校验
function validate(){
  if(monitor.recivedData.length<=0){
    monitor.lost ++
    file.append('\n')
    file.append(`这是发送的第${monitor.count}包`)
    file.append(`这是丢失的第${monitor.lost}包`)
    return
  }
  if(monitor.recivedData != monitor.sendData){
    monitor.errp ++
    file.append('\n')
    file.append(`这是发送的第${monitor.count}包`)
    file.append(`这是错误的第${monitor.errp}包`)
    // file.append('数据接收: ' + monitor.recivedData)
    prtErr()
  }

}
function prtErr(){
  let c = ""
  let d = ""
  let cc = "" ,dd = ""
  for (let i = 0; i < monitor.sendData.length; i++) {
    const sch = monitor.sendData.charCodeAt(i).toString(16)
    const rch = monitor.recivedData.charCodeAt(i).toString(16)
    if(sch == rch){
      c += chalk.dim.blue(rch) + " "
      
    }else{
      c += chalk.dim.red(rch) + " "
    }
    d += chalk.dim.blue(sch) + " "

    cc += rch + " "
    dd += sch + " "
  }
  console.log("发送：",d)
  console.log("接收：",c)
  file.append("发送：" + dd)
  file.append("接收：" + cc)
}
//首次发送
sendMsg()
//接收端
port.on('data', function(data) {
  monitor.recivedData += data
  //判断是否足够发送的数据量
  if(monitor.recivedData.length != monitor.sendData.length)
    return
  // console.log('数据接收: ' + monitor.recivedData)
  //校验
  validate()
});
setInterval(() => {
  monitor.timer -=50
  //判断时间是否到期
  if(monitor.timer<=0){
    validate()
    sendMsg()
  }
}, 50);
setInterval(() => {
  summary()
}, config.summary*1000);
function summary(){
  file.append(`共发出${monitor.count}包。`);
  file.append(`丢失${monitor.lost}包，丢包率${Math.round((monitor.lost/monitor.count)*100)}%。`);
  file.append(`错误${monitor.errp}包，错误率${Math.round((monitor.errp/monitor.count)*100)}%。`);
}

//销毁前回调
process.on('SIGINT', function () {
  summary()
  process.exit();
});
